#!/usr/bin/env python3
"""
长文本处理器 - 格式支持检测脚本
用于检查各种文件格式的支持情况和依赖库状态
"""

import sys
from pathlib import Path

# 将项目根目录添加到 Python 路径
current_dir = Path(__file__).parent
sys.path.insert(0, str(current_dir))

def check_dependencies():
    """检查必需的依赖库"""
    print("=" * 60)
    print("依赖库检查")
    print("=" * 60)
    
    dependencies = {
        'PyPDF2': 'PDF文件支持',
        'python-docx': 'DOCX文件支持 (导入名: docx)',
        'openpyxl': 'Excel文件支持',
        'pdfplumber': 'PDF文件支持 (备用方案)',
        'beautifulsoup4': 'HTML文件支持 (导入名: bs4)',
    }
    
    results = {}
    
    for lib, description in dependencies.items():
        import_name = lib
        if 'docx' in lib:
            import_name = 'docx'
        elif 'beautifulsoup' in lib:
            import_name = 'bs4'
            
        try:
            if import_name == 'PyPDF2':
                import PyPDF2
                version = PyPDF2.__version__ if hasattr(PyPDF2, '__version__') else '未知'
            elif import_name == 'docx':
                import docx
                version = docx.__version__ if hasattr(docx, '__version__') else '未知'
            elif import_name == 'openpyxl':
                import openpyxl
                version = openpyxl.__version__
            elif import_name == 'pdfplumber':
                import pdfplumber
                version = pdfplumber.__version__ if hasattr(pdfplumber, '__version__') else '未知'
            elif import_name == 'bs4':
                import bs4
                version = bs4.__version__ if hasattr(bs4, '__version__') else '未知'
            
            results[lib] = ('✅', f'已安装 (版本: {version})', description)
            print(f"✅ {lib:20s} - {description:30s} [版本: {version}]")
        except ImportError:
            results[lib] = ('❌', '未安装', description)
            print(f"❌ {lib:20s} - {description:30s} [未安装]")
    
    print()
    return results

def test_long_text_processor():
    """测试LongTextProcessor的实际功能"""
    print("=" * 60)
    print("LongTextProcessor 功能测试")
    print("=" * 60)
    
    # 尝试导入
    try:
        # 尝试从 mm_story_agent.utils 导入
        print("尝试从 mm_story_agent.utils 导入...")
        from mm_story_agent.utils.long_text_processor import LongTextProcessor
        print("✅ LongTextProcessor 导入成功\n")
        
        processor = LongTextProcessor()
        
        # 测试各种格式
        test_cases = [
            ('.txt', 'TXT文本文件', True),
            ('.md', 'Markdown文件', True),
            ('.pdf', 'PDF文件', 'PyPDF2'),
            ('.docx', 'Word文档', 'python-docx'),
        ]
        
        print("支持的文件格式:")
        print("-" * 60)
        
        for ext, desc, requirement in test_cases:
            if requirement is True:
                status = "✅ 完全支持（无需额外依赖）"
            else:
                try:
                    if 'PyPDF2' in requirement:
                        import PyPDF2
                        status = "✅ 支持（已安装依赖）"
                    elif 'docx' in requirement:
                        import docx
                        status = "✅ 支持（已安装依赖）"
                except ImportError:
                    status = f"⚠️  需要安装: {requirement}"
            
            print(f"{ext:8s} - {desc:20s} {status}")
        
        print()
        
    except ImportError as e:
        print(f"❌ 无法导入 LongTextProcessor: {e}")
        print()
        print("可能的原因：")
        print("1. mm_story_agent 模块不在当前目录")
        print("2. 文件路径不正确")
        print()
        print("请检查文件结构：")
        print("项目根目录/")
        print("├── check_format_support.py  (本脚本)")
        print("└── mm_story_agent/")
        print("    └── utils/")
        print("        └── long_text_processor.py")
        print()
        return False
    
    return True

def generate_installation_guide(results):
    """生成安装指南"""
    print("=" * 60)
    print("安装指南")
    print("=" * 60)
    
    missing = [lib for lib, (status, _, _) in results.items() if status == '❌']
    
    if not missing:
        print("✅ 所有依赖都已安装！")
        print()
        return
    
    print("缺少以下依赖库，请执行以下命令安装：\n")
    
    # 基础安装
    print("【方案1: 一次性安装所有依赖】")
    print("-" * 60)
    install_cmd = "pip install " + " ".join(missing)
    print(install_cmd)
    print()
    
    # 分步安装
    print("【方案2: 按需安装】")
    print("-" * 60)
    for lib, (status, _, description) in results.items():
        if status == '❌':
            print(f"# {description}")
            print(f"pip install {lib}")
            print()
    
    # 创建requirements.txt
    print("【方案3: 使用requirements.txt】")
    print("-" * 60)
    print("创建 requirements.txt 文件，内容如下：")
    print()
    for lib in missing:
        if 'PyPDF2' in lib:
            print(f"{lib}>=3.0.0")
        elif 'docx' in lib:
            print(f"{lib}>=0.8.11")
        elif 'openpyxl' in lib:
            print(f"{lib}>=3.0.0")
        elif 'pdfplumber' in lib:
            print(f"{lib}>=0.9.0")
        elif 'beautifulsoup' in lib:
            print(f"{lib}>=4.9.0")
    
    print("\n然后执行：")
    print("pip install -r requirements.txt")
    print()

def check_file_structure():
    """检查文件结构"""
    print("=" * 60)
    print("文件结构检查")
    print("=" * 60)
    
    current_dir = Path(__file__).parent
    long_text_path = current_dir / "mm_story_agent" / "utils" / "long_text_processor.py"
    
    print(f"当前脚本位置: {Path(__file__).absolute()}")
    print(f"预期的 long_text_processor.py 位置:")
    print(f"  {long_text_path}")
    
    if long_text_path.exists():
        print(f"\n✅ 找到文件！")
        file_size = long_text_path.stat().st_size
        print(f"   文件大小: {file_size / 1024:.2f} KB")
    else:
        print(f"\n❌ 文件不存在！")
        print(f"\n请检查文件是否在正确位置：")
        print(f"mm_story_agent/utils/long_text_processor.py")
        
        # 尝试查找文件
        print(f"\n正在搜索 long_text_processor.py...")
        found_files = list(current_dir.rglob("long_text_processor.py"))
        if found_files:
            print(f"找到以下匹配文件：")
            for f in found_files:
                print(f"  - {f.relative_to(current_dir)}")
        else:
            print(f"未找到 long_text_processor.py 文件")
    
    print()

def main():
    """主函数"""
    print("\n" + "=" * 60)
    print("长文本处理器 - 格式支持检测")
    print("=" * 60)
    print()
    
    # 0. 检查文件结构
    check_file_structure()
    
    # 1. 检查依赖
    results = check_dependencies()
    
    # 2. 测试处理器
    test_long_text_processor()
    
    # 3. 生成安装指南
    generate_installation_guide(results)
    
    print("=" * 60)
    print("检测完成")
    print("=" * 60)
    print("\n说明：")
    print("- TXT/MD 格式: 无需额外依赖，开箱即用")
    print("- PDF 格式: 需要 PyPDF2 或 pdfplumber")
    print("- DOCX 格式: 需要 python-docx")
    print("- Excel 格式: 需要 openpyxl (如需扩展)")
    print("- HTML 格式: 需要 beautifulsoup4 (如需扩展)")
    print()

if __name__ == "__main__":
    main()